<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
</head>

<body>
	<script>
		let activeEffect;

		const effect = (fn) => {

			const effectFn = () => {
				activeEffect = fn;
				return fn()
			}
			effectFn()

			return effectFn
		}



		const targetMap = new Map();
		const track = (target, key) => {
			if (!activeEffect) {
				return;
			}
			let depsMap = targetMap.get(target);
			if (!depsMap) {
				depsMap = new Map();
				targetMap.set(target, depsMap)
			}

			let deps = depsMap.get(key);
			if (!deps) {
				deps = new Set();
				depsMap.set(key, deps)
			}
			// 保存现有的effect函数
			deps.add(activeEffect)
			// debugger
		}


		const trigger = (target, key) => {
			const depsMap = targetMap.get(target);
			if (!depsMap) {
				return;
			}

			const deps = depsMap.get(key);
			if (!deps) {
				return;
			}

			deps.forEach(effectFn => effectFn())
		}
		const reactive = target => {
			return new Proxy(target, {
				get(target, key, receiver) {
					// console.log("target:", target)
					// console.log("key:", key)
					// console.log("receiver:", receiver)
					track(target, key)
					console.log(`访问了${key}属性,获取它的值为${target[key]}`)
					// return target[key]
					return Reflect.get(target, key, receiver)
				},
				set(target, key, value, receiver) {
					console.log(`将${key}由->${target[key]}->设置成->${value}`)
					let res = Reflect.set(target, key, value, receiver);
					trigger(target, key)
					// target[key] = value;
					return res
				}
			})
		}




		const a = reactive({
			count: 0
		})

		effect(() => {
			console.log("count被修改成：", a.count)
		})

		a.count = 10;



	</script>
</body>

</html>